﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using HZH_Controls;
using NDK.Module.DAL;
using NDK.Utils;
using static NDK.Module.Model.Common;

namespace NDK.Module.Model.Quebec
{
    public class CommunicationProtocol
    {

    }


    #region Algo


    public class ReturnProtocol
    {
        public string Function { get; set; }
        public ReturnState State { get; set; }
        public string Other { get; set; }

        public static ReturnProtocol GetReturnModel(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;
            else
            {
                str.Replace("/r/n", "|");
                var strSplit = str.Split('|');
                if (strSplit.Length > 0)
                {
                    var command = strSplit[0];
                    var rtn = command.Split(',');
                    if (rtn.Length >= 2)
                    {
                        var rtnProtocol = new ReturnProtocol() { Function = rtn[0] };
                        var stateStr = rtn[1];

                        if (stateStr.Equals(ReturnState.OK.ToString()))
                            rtnProtocol.State = ReturnState.OK;
                        else if (stateStr.Equals(ReturnState.GrabEnd.ToString()))
                            rtnProtocol.State = ReturnState.GrabEnd;
                        else if (stateStr.Equals(ReturnState.Ready.ToString()))
                            rtnProtocol.State = ReturnState.Ready;
                        else
                            rtnProtocol.State = ReturnState.Undefined;
                        return rtnProtocol;
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
        }

        public override string ToString()
        {
            string str = "";
            str += Function + ",";
            str += State + ",";
            str += Other;
            return str;
        }
    }

    public class ReturnResultProtocol
    {
        public string BarCode;
        public string StationNO;
        public MeasureProduct measureProduct = new MeasureProduct();

        public static ReturnResultProtocol GetReturnResult(string str) //Barcode,StationNO,FAI1#FAI2#FAI3,1.2#1.3#1.4
        {
            string Header = ",SN,";
            List<DataItem> Res = new List<DataItem>();
            if (string.IsNullOrEmpty(str))
                return null;
            else
            {
                str.Replace("/r/n", "|");
                var strSplit = str.Split('|');
                if (strSplit.Length > 0)
                {
                    var result = strSplit[0];
                    var rtn = result.Split(',');

                    if (rtn.Length >= 4)
                    {
                        var rtnResultProtocol = new ReturnResultProtocol() { BarCode = rtn[0], StationNO = rtn[1] };

                        string[] FAIName = rtn[2].Split('#');//.Split(',')[0].Trim()
                        string[] FAIValue = rtn[3].Split('#');//.Split(',')[1].Trim()

                        if (FAIName.Count().Equals(FAIValue.Count())) //数据和尺寸号个数一致
                        {
                            for (int i = 0; i < FAIName.Count(); i++)
                            {
                                DataItem item = new DataItem { Name = FAIName[i], Value = Math.Abs(FAIValue[i].ToDouble()) };
                                rtnResultProtocol.measureProduct.MeasureData.Add(item);
                            }
                            MeasureSizeServices measureSizeService = new MeasureSizeServices();
                            List<MeasureSize> measureSizeList = new List<MeasureSize>();
                            measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(CurProType, 1);
                            foreach (var item in measureSizeList)
                            {
                                if (item.SizeName == "FAI12-PPG")
                                {
                                    continue;
                                }
                                Header += item.SizeName + ",";
                            }
                            //创建存数据的路径
                            string CSVDataDirectory = "";
                            CSVDataDirectory = dataSavePath + "\\" + ProjectName + "\\" + DateTime.Now.ToString("yyyy-MM") + "\\" + "数据记录";
                            if (!Directory.Exists(CSVDataDirectory))
                            {
                                Directory.CreateDirectory(CSVDataDirectory);

                            }
                            string fullPath = CSVDataDirectory + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + "-Data" + ".csv";
                            if (!Directory.Exists(fullPath))
                            {
                                FileUtils.AppendText(fullPath, Header + "\r\n");
                            }

                            if (measureSizeList.Count - 1 == rtnResultProtocol.measureProduct.MeasureData.Count)
                            {
                                foreach (var item in measureSizeList)//rtnResultProtocol.measureProduct.MeasureData
                                {
                                    //if (item.IsShow == false)
                                    //{
                                    //    continue;
                                    //}
                                    for (int i = 0; i < rtnResultProtocol.measureProduct.MeasureData.Count; i++)
                                    {
                                        if ((item.SizeName == rtnResultProtocol.measureProduct.MeasureData[i].Name))
                                        {
                                            Res.Add(rtnResultProtocol.measureProduct.MeasureData[i]);
                                            WriteLogToTxt(rtnResultProtocol.measureProduct.MeasureData[i].Name.ToString() + "," + rtnResultProtocol.measureProduct.MeasureData[i].Value.ToString() + "\r\n");
                                            rtnResultProtocol.measureProduct.MeasureData.Remove(rtnResultProtocol.measureProduct.MeasureData[i]);
                                            //rtnResultProtocol.measureProduct.MeasureData.AddRange(Res);
                                            break;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }
                                Res.Count();
                                rtnResultProtocol.measureProduct.MeasureData.Clear();
                                rtnResultProtocol.BarCode = rtn[0];
                                rtnResultProtocol.StationNO = rtn[1];
                                rtnResultProtocol.measureProduct.MeasureData.AddRange(Res);
                            }
                            else
                            {

                                List<string> list = new List<string>();
                                for (int i = 0; i < rtnResultProtocol.measureProduct.MeasureData.Count; i++)
                                {
                                    list.Add(rtnResultProtocol.measureProduct.MeasureData[i].Name);

                                }
                                for (int i = 0; i < measureSizeList.Count; i++)
                                {
                                    if (list.Contains(measureSizeList[i].SizeName))
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        if (measureSizeList[i].SizeName == "FAI12-PPG" || measureSizeList[i].SizeName == "FAI-RANDOM-SAMPLE")
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            DataItem item = new DataItem { Name = measureSizeList[i].SizeName, Value = 9999 };
                                            rtnResultProtocol.measureProduct.MeasureData.Add(item);
                                        }

                                    }
                                }
                                string values = "切割后数据" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + rtn[0] + ",";
                                foreach (var item in measureSizeList)//rtnResultProtocol.measureProduct.MeasureData
                                {
                                    //if (item.IsShow == false)
                                    //{
                                    //    continue;
                                    //}
                                    for (int i = 0; i < rtnResultProtocol.measureProduct.MeasureData.Count; i++)
                                    {
                                        if ((item.SizeName == rtnResultProtocol.measureProduct.MeasureData[i].Name))
                                        {
                                            Res.Add(rtnResultProtocol.measureProduct.MeasureData[i]);
                                            values += rtnResultProtocol.measureProduct.MeasureData[i].Value.ToString("0.0000") + ",";
                                            WriteLogToTxt(rtnResultProtocol.measureProduct.MeasureData[i].Name.ToString() + "," + rtnResultProtocol.measureProduct.MeasureData[i].Value.ToString() + "\r\n");
                                            rtnResultProtocol.measureProduct.MeasureData.Remove(rtnResultProtocol.measureProduct.MeasureData[i]);
                                            //rtnResultProtocol.measureProduct.MeasureData.AddRange(Res);
                                            break;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }
                                Res.Count();
                                FileUtils.AppendText(fullPath, values + "\r\n");
                                rtnResultProtocol.measureProduct.MeasureData.Clear();
                                rtnResultProtocol.BarCode = rtn[0];
                                rtnResultProtocol.StationNO = rtn[1];
                                rtnResultProtocol.measureProduct.MeasureData.AddRange(Res);
                            }

                        }
                        else
                        {
                            return null;
                        }
                        return rtnResultProtocol;
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
        }
        private static void WriteLogToTxt(string strLog)
        {

            String System_Now_Time = null;
            String File_Create_Time = null;

            System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
            File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
            string logDocument = File_Create_Time + ".txt";

            string str = Process.GetCurrentProcess().MainModule.FileName;
            string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\" + "VisionRes";//VisionSendMessage";
            if (!Directory.Exists(logFilePath))
            {
                Directory.CreateDirectory(logFilePath);
            }
            logFilePath = logFilePath + "//" + logDocument;
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(System_Now_Time + ":   " + strLog);
            sw.Flush();
            sw.Close();
            fs.Close();

        }
    }

    public enum ReturnState
    {
        Undefined, Ready, GrabEnd, OK
    }
    #endregion

}

